package com.naiterui.ehp.bs.im.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.bo.im.SessionDetailBO;
import com.naiterui.ehp.bp.bo.im.UserSessionStatusBO;
import com.naiterui.ehp.bs.im.exception.NaiteruiIMException;
import com.naiterui.ehp.bs.im.network.protocl.CustomizedMessage;
import com.naiterui.ehp.bs.im.network.protocl.SessionDetails;
import com.naiterui.ehp.bs.im.repository.mongo.SessionDao;
import com.naiterui.ehp.bs.im.service.ISessionService;
import com.naiterui.ehp.bs.im.service.message.handler.SessionHandler;
import com.naiterui.ehp.bs.im.utils.Constants;

@Service
public class SessionServiceImpl implements ISessionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SessionServiceImpl.class);

    private static final Integer PAY_TYPE_FREE = 0;

    private final SessionHandler sessionHandler;
    private final SessionDao sessionDao;

    public SessionServiceImpl(SessionHandler sessionHandler, SessionDao sessionDao) {
        this.sessionHandler = sessionHandler;
        this.sessionDao = sessionDao;
    }

    @Override
    public List<UserSessionStatusBO> isSessionAlive(List<Long> doctorIds, Long patientId) {
        List<UserSessionStatusBO> statusList = new ArrayList<>();
        /*
         * 判断当前是否有进行中的会话
         */
        for (Long doctorId : doctorIds) {
            UserSessionStatusBO status = new UserSessionStatusBO();
            String sessionKey = SessionHandler.getSessionKey(doctorId, patientId);
            status.setDoctorId(doctorId);
            status.setPatientId(patientId);
            status.setAlive(RedisUtil.hashOps().hexist(sessionKey, "sessionId"));
            statusList.add(status);
        }
        return statusList;
    }

    @Override
    public void finishSessionByDeletePatient(Long doctorId, Long patientId, Integer triggerSource) {
        String sessionKey = SessionHandler.getSessionKey(doctorId, patientId);
        if (RedisUtil.hashOps().hexist(sessionKey, "sessionId")) {
            String sessionId = RedisUtil.hashOps().hget(sessionKey, "sessionId");
            try {
                SessionDetails session = sessionDao.findSessionById(sessionId);
                sessionHandler.finishSession(sessionId, doctorId, patientId, PAY_TYPE_FREE, true, true, session, triggerSource);
            } catch (NaiteruiIMException e) {
                LOGGER.error("结束会话 finishSession异常 ");
            }
        }

    }

    @Override
    public List<SessionDetailBO> sessionDetailList(String sessionIds) {
        List<String> sessionIdList = Arrays.asList(sessionIds.split(","));
        List<SessionDetails> sessionDetails = sessionDao.findSessionByIdIn(sessionIdList);
        List<SessionDetailBO> result = new ArrayList<>();
        for (SessionDetails sessionDetail : sessionDetails) {
            SessionDetails.Msg msg = sessionDetail.getFirstMsg();
            CustomizedMessage cMsg = new CustomizedMessage();
            if (msg.getType() == Constants.MESSAGE_TYPE_REMIND_PATIENTS_FILL_MEDICAL_RECORD) {
                cMsg = (CustomizedMessage)msg.getContent();
            }
            result.add(SessionDetailBO.builder().beginTime(sessionDetail.getBeginTime())
                .free(null == sessionDetail.getConsultPayType()
                    || sessionDetail.getConsultPayType().equals(Constants.CONSULT_PAY_TYPE_FREE))
                .consultSessionId(sessionDetail.getConsultSessionId())
                .containRecom(null != sessionDetail.getContainRecom()
                    && sessionDetail.getContainRecom().equals(SessionDetails.CONTAIN_RECOM_YES))
                .containRecord(null != sessionDetail.getContainRecom()
                    && sessionDetail.getContainRecom().equals(SessionDetails.CONTAIN_RECOM_YES))
                .endTime(sessionDetail.getEndTime()).sessionId(sessionDetail.getSessionId())
                .specificMessageType(cMsg.getSpecificMessageType()).recordId(cMsg.getRecordId()).build());
        }
        return result;
    }
}
